package com.jeesite.modules.ic.api;

import com.icecold.utils.HtmlUtil;
import com.jeesite.common.config.Global;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.image.ImageUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.ueditor.define.FileType;
import com.jeesite.modules.component.CatchService;
import com.jeesite.modules.config.Result;
import com.jeesite.modules.ic.entity.IcUser;
import com.jeesite.modules.ic.service.IcUserService;
import com.jeesite.modules.mo.entity.MoUserDevice;
import com.jeesite.modules.mo.service.MoUserDeviceService;
import com.jeesite.modules.pt.dao.PtSettingDao;
import com.jeesite.modules.rt.dao.RtAskDao;
import com.jeesite.modules.rt.entity.RtAsk;
import com.jeesite.modules.rt.entity.RtGroup;
import com.jeesite.modules.rt.entity.RtXieyi;
import com.jeesite.modules.rt.service.RtAskService;
import com.jeesite.modules.rt.service.RtGroupService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/app/api")
@Slf4j
public class ApiUserController {

    @Autowired
    private IcUserService icUserService;
    @Autowired
    private RtGroupService rtGroupService;
    @Autowired
    private MoUserDeviceService moUserDeviceService;
    @Autowired
    private RtAskService rtAskService;
    @Autowired
    private RtAskDao rtAskDao;
    @Autowired
    private CatchService catchService;

    @Autowired
    private PtSettingDao ptSettingDao;

    @Value("${self.baseUrl}")
    private String selfBaseUrl;

    @Value("${pic.baseUrl}")
    private String houtaiPicBaseUrl;

    /**
     * 绑定支付宝手机号
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/bindZhifubaoMobile")
    public Result bindZhifubaoMobile(HttpServletRequest request, HttpServletResponse response){
        String userId = getUserId(request);
        String mobile = request.getParameter("mobile");
        String shoukuanName = request.getParameter("shoukuanName");
        if(StringUtils.isEmpty(mobile) || StringUtils.isEmpty(shoukuanName)){
            return Result.buildFailureResult("请填写完整的支付宝账号信息");
        }
        IcUser icUser = icUserService.get(userId);
        icUser.setShoukuanName(shoukuanName);
        icUser.setZhifubaoMobile(mobile);
        icUserService.save(icUser);
        return Result.buildSuccessResult(icUser);
    }



    /**
     * 常见问题
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/rtAskList")
    public Result rtAskList(HttpServletRequest request, HttpServletResponse response){
        List<RtAsk> list = rtAskService.findList(new RtAsk());
        for (RtAsk rtAsk : list){
            String content = rtAsk.getContent();
            content = HtmlUtil.repairContent(content,selfBaseUrl);
            rtAsk.setContent(content);
        }
        return Result.buildSuccessResult(list);
    }

    public static void main(String[] args) {
        String s = "<!--HTML--><p>&nbsp;<strong> 1、扫描设备上的二维码下载app。</strong></p><p><strong>&nbsp;</strong></p><p><strong>&nbsp;2、设备通过网线连接到光猫或者路由器的网口。登录光猫超级账号，下面一般是光猫自带密码，如果不对请联系当地装维。</strong></p><p><strong>&nbsp;</strong></p><p><strong>&nbsp;3、光猫管理地址<br/></strong></p><p><strong>&nbsp; &nbsp; &nbsp; &nbsp;3.1、默认是<span style=\"color: rgb(255, 0, 0);\">192.168.1.1</span>或者<span style=\"color: rgb(255, 0, 0);\">192.168.0.1</span>（具体看光猫背面信息）接入光猫的wifi或者用网线接入LAN口，自动获取IP地址，打开浏览器，输入http://<span style=\"color: rgb(255, 0, 0);\">192.168.1.1</span><span style=\"color: rgb(255, 0, 0);\"></span></strong></p><p><strong>&nbsp; &nbsp; &nbsp; 3.2、使用超级用户账号密码登录，不同型号和不同地区可能不一样，可以百度查询或者联系服务提供商&nbsp;</strong></p><p><strong>&nbsp; &nbsp; &nbsp; &nbsp; 电信超级账号：telecomadmin&nbsp;<strong style=\"text-wrap: wrap;\">&nbsp;&nbsp; 密码：nE7jA%5m</strong></strong></p><p><strong>&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;</strong><strong>移动超级账号：CMCCAdmin&nbsp;<strong>&nbsp; &nbsp; &nbsp; 密码：aDm8H%MdA</strong></strong></p><p><strong>&nbsp; &nbsp; &nbsp; &nbsp;</strong><strong>联通超级账号：CUAdmin&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;</strong><strong>密码：CUAdmin</strong></p><p><br/></p><p style=\"text-wrap: wrap;\"><strong>4、修改网络类型<br/></strong></p><p><strong>&nbsp;4.1 如果盒子连接的是光猫，进入光猫，应用</strong></p><p><img src=\"/js/userfiles/system/images/20241119/123213_$1732013339487080496.png\" title=\"123213_$1732013339487080496.png\" alt=\"123213.png\"/></p><p><strong>&nbsp;4.2&nbsp;如果盒子连接的是路由器，光猫拨号</strong></p><p><br/></p>";
        String s1 = HtmlUtil.repairContent(s,"https://llk.zzlmvip.com");
        System.out.println(s1);
    }

    /**
     * 团员明细
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/tuanyuanList")
    public Result tuanyuanList(HttpServletRequest request, HttpServletResponse response){
        String userId = getUserId(request);
        IcUser icUser = new IcUser();
        icUser.setParentUserId(userId);
        List<IcUser> list = icUserService.findList(icUser);
        for(IcUser u : list){
            String deviceUserId = u.getId();
            MoUserDevice moUserDevice = new MoUserDevice();
            moUserDevice.setUserId(deviceUserId);
            long count = moUserDeviceService.findCount(moUserDevice);
            u.setDeviceNum(new Long(count).intValue());
        }
        return Result.buildSuccessResult(list);
    }

    public String getUserId(HttpServletRequest request){
        Object user_id = request.getAttribute("user_id");
        if(user_id!=null){
            return user_id.toString();
        }
        return request.getParameter("userId");
    }

    @RequestMapping("/userInfo")
    public Result getUserInfo(IcUser icUser, HttpServletRequest request, HttpServletResponse response){
        String user_id = getUserId(request);
        IcUser user = icUserService.get(user_id);
        IcUser icUser1 = new IcUser();
        icUser1.setParentUserId(user_id);
        user.setYaoqingRenNum(new Long(icUserService.findCount(icUser1)).intValue());
        RtGroup rtGroup = new RtGroup();
        rtGroup.setUserId(user_id);
        rtGroup.setName("默认分组");
        long count = rtGroupService.findCount(rtGroup);
        if(count<=0){
            rtGroupService.save(rtGroup);
        }

        return Result.buildSuccessResult(user);
    }

    @RequestMapping("/updateUserInfo")
    public Result updateUserInfo(IcUser icUser, HttpServletRequest request, HttpServletResponse response){
        String user_id = request.getAttribute("user_id").toString();
        //代理商提成
        Double agentRatio = icUser.getAgentRatio();
        if(agentRatio!=null){
            //平台设置的最高提成
            IcUser userOld = icUserService.get(user_id);
            if(userOld.getMaxTicheng()!=null){
                if(agentRatio>userOld.getMaxTicheng()){
                   return Result.buildFailureResult("提成比例过高，请调整提成比例");
                }
            }else{
                String valueByKey = ptSettingDao.getValueByKey("max_daili_ticheng");
                if(StringUtils.isNotBlank(valueByKey)){
                    if(agentRatio>Double.parseDouble(valueByKey)){
                        return Result.buildFailureResult("提成比例过高，请调整提成比例");
                    }
                }
            }

        }

        icUser.setId(user_id);
        icUser.setUpdateTime(new Date());
        icUserService.save(icUser);
        return Result.buildSuccessResult();
    }

    @RequestMapping("uploadFile")
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        String originFileName = file.getOriginalFilename();
        String suffix = FileType.getSuffixByFilename(originFileName);
        String picName= IdGen.uuid();
        String destFileName = "/home/java/project/liuliangka/userfiles/system/pic/" + picName;
        destFileName = destFileName + suffix;
        File destFile = new File(destFileName);
        destFile.getParentFile().mkdirs();
        try {
            file.transferTo(destFile);
            ImageUtils.thumbnails(destFile,1000,-1,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String lineUrl = houtaiPicBaseUrl+"/js/userfiles/system/pic/"+picName+suffix;
        return Result.buildSuccessResult(lineUrl);
    }
}
